/*******************************************************************************
 * Copyright (c) 2006 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
package org.cmoine.perspectiveshare.importWizards;

import static org.eclipse.core.runtime.IStatus.ERROR;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;

import org.cmoine.perspectiveshare.Activator;
import org.cmoine.perspectiveshare.model.DocumentRoot;
import org.cmoine.perspectiveshare.model.util.PerspectivesXMLProcessor;
import org.cmoine.perspectiveshare.perspectives.PerspectiveSharePerspectiveFactory;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.window.Window;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.IImportWizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.dialogs.ListDialog;

public class PerspectiveShareImportWizard extends Wizard implements IImportWizard {
	
	PerspectiveShareImportWizardPage mainPage;
    private IWorkbench workbench;

	public PerspectiveShareImportWizard() {
		super();
	}

	/* (non-Javadoc)
	 * @see org.eclipse.jface.wizard.Wizard#performFinish()
	 */
	@Override
    public boolean performFinish() {
        try {
            Properties props=new Properties();
            props.load(new FileInputStream(new File(mainPage.getFilePath())));
            List<DocumentRoot> roots=new ArrayList<DocumentRoot>();
            for (Object key : props.keySet()) {
                if (((String) key).matches("/instance/org.eclipse.ui.workbench/(.*)_persp")) { //$NON-NLS-1$
                    String value=(String) props.get(key);
                    Resource res=new PerspectivesXMLProcessor().load(new ByteArrayInputStream(value.getBytes()), new HashMap<Object, Object>());

                    DocumentRoot root=(DocumentRoot) res.getContents().get(0);
                    roots.add(root);
                }
            }
            if (roots.isEmpty()) {
                MessageDialog.openError(getShell(), Messages.errorImportingTitle, Messages.noPerspectiveToImportMessage);
                return false;
            } else {
                DocumentRoot root;
                if (roots.size() == 1) {
                    root=roots.get(0);
                } else {
                    ListDialog dialog=new ListDialog(getShell());
                    dialog.setMessage(Messages.perspectiveSelectionDialogMessage);
                    dialog.setLabelProvider(new LabelProvider() {
                        @Override
                        public String getText(Object element) {
                            return ((DocumentRoot) element).getPerspective().getDescriptor().getLabel();
                        }
                    });
                    dialog.setContentProvider(ArrayContentProvider.getInstance());
                    dialog.setInput(roots);
                    if (dialog.open() == Window.CANCEL)
                        return false;
                    root=(DocumentRoot) dialog.getResult()[0];
                }
                PerspectiveSharePerspectiveFactory.setCode(new CodeGenerator(root).generate());
                IWorkbenchWindow window=workbench.getActiveWorkbenchWindow();
                IWorkbenchPage page=window.getActivePage();
                page.setPerspective(workbench.getPerspectiveRegistry().findPerspectiveWithId(PerspectiveSharePerspectiveFactory.ID));
                page.resetPerspective();
                return true;
            }
        } catch (FileNotFoundException e) {
            Activator.log(ERROR, "Failed to set layout", e); //$NON-NLS-1$
        } catch (IOException e) {
            Activator.log(ERROR, "Failed to set layout", e); //$NON-NLS-1$
        }
        return false;
	}

    /*
     * (non-Javadoc)
     * 
     * @see org.eclipse.ui.IWorkbenchWizard#init(org.eclipse.ui.IWorkbench, org.eclipse.jface.viewers.IStructuredSelection)
     */
	public void init(IWorkbench workbench, IStructuredSelection selection) {
        this.workbench=workbench;
        setWindowTitle(Messages.wizardImportTitle); // NON-NLS-1
		setNeedsProgressMonitor(true);
		mainPage = new PerspectiveShareImportWizardPage(Messages.wizardImportMessage,selection); //NON-NLS-1
	}
	
	/* (non-Javadoc)
     * @see org.eclipse.jface.wizard.IWizard#addPages()
     */
    @Override
    public void addPages() {
        super.addPages(); 
        addPage(mainPage);        
    }
}
